import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';

/**
 * 路由配置 - 使用懒加载和代码分割
 * 
 * 优化策略：
 * 1. 所有页面组件使用动态导入（懒加载）
 * 2. 使用webpack魔术注释命名chunk，便于调试和缓存
 * 3. 相关页面可以分组到同一个chunk（如auth相关）
 */

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      // MainLayout也懒加载，减小初始bundle
      component: () => import(/* webpackChunkName: "layout" */ '../layouts/MainLayout.vue'),
      children: [
        {
          path: '',
          name: 'home',
          component: () => import(/* webpackChunkName: "home" */ '../views/HomePage.vue'),
          meta: { 
            title: '首页',
            // 预加载常用页面
            preload: ['submit', 'history']
          },
        },
        {
          path: 'submit',
          name: 'submit',
          component: () => import(/* webpackChunkName: "essay-submit" */ '../views/EssaySubmitPage.vue'),
          meta: { 
            requiresAuth: true, 
            title: '提交作文',
            // 提交作文后通常会去批改结果页，预加载它
            preload: ['correction']
          },
        },
        {
          path: 'correction/:essayId',
          name: 'correction',
          component: () => import(/* webpackChunkName: "correction-result" */ '../views/CorrectionResultPage.vue'),
          meta: { 
            requiresAuth: true, 
            title: '批改结果',
            // 查看结果后可能去历史记录
            preload: ['history']
          },
        },
        {
          path: 'history',
          name: 'history',
          component: () => import(/* webpackChunkName: "history" */ '../views/HistoryPage.vue'),
          meta: { 
            requiresAuth: true, 
            title: '历史记录',
            // 历史记录页可能跳转到提交或结果页
            preload: ['submit', 'correction']
          },
        },
        {
          path: 'profile',
          name: 'profile',
          component: () => import(/* webpackChunkName: "profile" */ '../views/ProfilePage.vue'),
          meta: { 
            requiresAuth: true, 
            title: '个人中心'
          },
        },
      ],
    },
    // 登录和注册页面不使用MainLayout
    // 将auth相关页面打包到同一个chunk
    {
      path: '/login',
      name: 'login',
      component: () => import(/* webpackChunkName: "auth" */ '../views/LoginPage.vue'),
      meta: { 
        guest: true, 
        title: '登录',
        // 登录页预加载注册页
        preload: ['register']
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import(/* webpackChunkName: "auth" */ '../views/RegisterPage.vue'),
      meta: { 
        guest: true, 
        title: '注册',
        // 注册页预加载登录页
        preload: ['login']
      },
    },
    // 404页面 - 独立chunk，优先级最低
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import(/* webpackChunkName: "not-found" */ '../views/NotFoundPage.vue'),
      meta: { title: '页面未找到' },
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();

  // 更新页面标题
  document.title = to.meta.title ? `${to.meta.title} - AI作文批改` : 'AI作文批改';

  // 需要认证的路由
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    console.log('[Router] Redirecting to login - authentication required');
    next({ name: 'login', query: { redirect: to.fullPath } });
    return;
  }

  // 游客路由（已登录用户访问登录/注册页时重定向到首页）
  if (to.meta.guest && userStore.isAuthenticated) {
    console.log('[Router] Redirecting to home - already authenticated');
    next({ name: 'home' });
    return;
  }

  next();
});

// 路由错误处理
router.onError((error) => {
  console.error('[Router] Navigation error:', error);
});

export default router;

